<template>
  <div class="weather-page">
    <div class="breadcrumb">
      <Breadcrumb :data="breadcrumbData"></Breadcrumb>
    </div>
    <main>
      <ul class="echarts-list">
        <li class="echarts-item">
          <forecast :forecasts="forecasts" :lives="lives"></forecast>
        </li>
        <li class="echarts-item">
          <environmental :climate="climate"></environmental>
        </li>
        <li class="echarts-item">
          <broken-line :options="windSpeedConfig"></broken-line>
        </li>
        <li class="echarts-item">
          <broken-line :options="temperatureConfig"></broken-line>
        </li>
        <li class="echarts-item">
          <broken-line :options="pm2Config"></broken-line>
        </li>
        <li class="echarts-item">
          <broken-line :options="dbConfig"></broken-line>
        </li>
        <li class="echarts-item">
          <broken-line :options="rhConfig"></broken-line>
        </li>
        <li class="echarts-item">
          <broken-line :options="pm10Config"></broken-line>
        </li>
        <li class="echarts-item">
          <span v-if="!alarmList.length" class="empty-text">暂无数据</span>
          <div class="title">
            <span>动态预警记录</span>
            <span class="icon-btn">
<!--              <i class="el-icon-setting" @click="handleSet"></i>-->
<!--              <i class="el-icon-time" @click="alarmVisible = true"></i>-->
            </span>
          </div>
          <div class="scroll-container" @mouseenter="handleMouseenter" @mouseleave="handleMouseleave">
            <div class="info-list">
              <div class="info-item" v-for="(item, index) in alarmList" :key="index">
                <span class="time">{{ item.modifyTime }}{{index}}</span>
                <span class="name">{{ alarmTypes[item.alarmType] || '' }}</span>
                <span class="detail">{{ item.alarmValue }}</span>
              </div>
            </div>
            <div v-if="hasCopy" class="info-list">
              <div class="info-item" v-for="(item, index) in alarmList" :key="index">
                <span class="time">{{ item.modifyTime }}{{index}}</span>
                <span class="name">{{ alarmTypes[item.alarmType] || '' }}</span>
                <span class="detail">{{ item.alarmValue }}</span>
              </div>
            </div>
          </div>
        </li>
      </ul>
    </main>
  </div>
</template>

<script>
import Breadcrumb from '@/components/public/Breadcrumb';
import brokenLine from '@/components/echarts/brokenLine';
import forecast from '@/components/project/weather/forecast';
import environmental from '@/components/project/weather/environmental';
import historyImage from '@/assets/images/history.png';

// 天气监测
export default {
  components: {
    brokenLine,
    forecast,
    Breadcrumb,
    environmental
  },
  data() {
    return {
      // 面包屑数据
      breadcrumbData: [
        {
          name: '环境管理',
        },
        {
          name: '天气监测'
        }
      ],
      // 预报天气信息数据
      forecasts: [],
      // 实况天气数据信息
      lives: [],
      alarmList: [],
      alarmTypes: {
        '1': 'tsp',
        '2': '温度',
        '3': '湿度',
        '4': '风向',
        '5': '大气',
        '6': '风速',
        '7': 'PM2.5',
        '8': 'PM10',
        '9': '噪音',
      },
      scrollId: null,
      hasCopy: false,
      envList: [],
      climate: {},
      // 城市code
      cityCode: '350200'
    };
  },
  computed: {
    projectId() {
      return this.$store.state.currentProjectId;
    },
    xAxisData() {
      return this.envList.map(v => v.time);
    },
    // 风速图表配置
    windSpeedConfig() {
      const type = 'windSpeed';
      const title = { text: '风速（m/s）' };
      const series = {
        name: title.text,
        ...this.setBg('rgba(69, 191, 161, .9)', 'rgba(69, 191, 161, .1)', 100),
        data: this.envList.map(v => v.windspeed),
      };
      return this.setConfig({ title, series, type });
    },
    // 设置温度图表配置
    temperatureConfig() {
      const type = 'temperature';
      const title = { text: '温度（℃）' };
      const series = {
        name: title.text,
        ...this.setBg('rgba(69, 191, 161, .9)', 'rgba(69, 191, 161, .1)', 220),
        data: this.envList.map(v => v.temp),
      };
      return this.setConfig({ title, series, type });
    },
    // 设置PM2.5图表配置
    pm2Config() {
      const type = 'pm2';
      const title = { text: 'PM2.5（ug/m³）' };
      const series = {
        name: title.text,
        ...this.setBg('rgba(198, 77, 208, .9)', 'rgba(198, 77, 208, .1)', 180),
        data: this.envList.map(v => v.pm25)
      };
      return this.setConfig({ title, series, type });
    },
    // 设置噪声图表配置
    dbConfig() {
      const type = 'db';
      const title = { text: '噪声（db）' };
      const series = {
        name: title.text,
        ...this.setBg('rgba(238, 51, 83, .9)', 'rgba(238, 51, 83, .1)', 200),
        data: this.envList.map(v => v.noise)
      };
      return this.setConfig({ title, series, type });
    },
    // 设置湿度图表配置
    rhConfig() {
      const type = 'rh';
      const title = { text: '湿度（%RH）' };
      const series = {
        name: title.text,
        ...this.setBg('rgba(255, 244, 99, .9)', 'rgba(255, 244, 99, .1)', 150),
        data: this.envList.map(v => v.hum)
      };
      return this.setConfig({ title, series, type });
    },
    // 设置pm10图表配置
    pm10Config() {
      const type = 'pm10';
      const title = { text: 'PM10（ug/m³）' };
      const series = {
        name: title.text,
        ...this.setBg('rgba(4, 101, 231, .9)', 'rgba(4, 101, 231, .1)'),
        data: this.envList.map(v => v.pm10)
      };
      return this.setConfig({ title, series, type });
    }
  },
  async created() {
    await this.getWeatherCode();
    this.getMonitorEnvor();
    this.getWeatherInfo();
    this.getWeatherInfo('base');
  },
  methods: {
    /**
     * 根据项目id获取天气code
     */
    async getWeatherCode() {
      const params = {
        projectId: this.projectId,
      };
      const { success, data: {
        data
      }} = await this.$Model.getWeatherCode(params);
      if (success && data) this.cityCode = data;
    },
    /**
     * 获取天气信息
     * @param extensions {String} 天气类型 all: 天气预报 base: 实时天气
     */
    async getWeatherInfo(extensions = 'all') {
      try {
        const result = await this.$axios({
          url: 'https://restapi.amap.com/v3/weather/weatherInfo',
          method: 'get',
          params: {
            key: 'dec2b0d6f41a26d4ee7ea697d406bee8',
            city: this.cityCode,
            extensions
          }
        });
        const { status, infocode, forecasts, lives } = result.data;
        if (status === '1' && String(infocode) === '10000') {
          if (extensions === 'all') {
            this.forecasts = forecasts || [];
            return;
          }
          this.lives = lives || [];
        }
      } catch (e) {}
    },
    async getMonitorEnvor() {
      const { success, data: {
        data
      }} = await this.$Model.getMonitorEnvor({
        projectId: this.projectId,
        pageNum: 1,
        pageSize: 500
      });
      if (success && data) {
        const list = data.list || [];
        this.envList = list.map(v => ({
          ...v,
          dataStr: v.time,
          time: v.time.replace(/\d{1,4}-\d{1,2}-\d{1,2}\s+/, '')
        }));
        if (this.envList.length) {
          const item = this.envList[0];
          const {
            windspeed,
            winddirection,
            temp,
            pm25,
            hum,
          } = item;
          this.climate = {
            ...item,
            temperature: temp,
            windSpeed: windspeed,
            humidity: hum,
            windDirection: winddirection,
            dust: pm25
          };
        }
      }
    },
    // 获取环境预警信息
    async getEnvirAlarmList() {
      const { success, data: {
        data
      }} = await this.$Model.getEnvirAlarmList({
        projectId: this.projectId,
        pageNum: 1,
        pageSize: 100
      });
      if (success && data) {
        this.alarmList = data.list || [];
        this.$nextTick(() => {
          this.setAlarmScroll();
        });
      }
    },
    /**
     * 查看历史记录
     * @param type {String} 配置类型
     */
    getHistory(type) {
      console.log('type', type);
    },
    /**
     * 设置图表背景
     * @param startVal {String} 起点样式
     * @param endVal {String} 结束点样式
     * @param warnVal {Number} 预警值
     */
    setBg(startVal, endVal, warnVal) {
      const options = {
        // areaStyle: {
        //   color: new this.$echarts.graphic.LinearGradient(0, 0, 0, 1, [{
        //     offset: 0,
        //     color: startVal
        //   }, {
        //     offset: 1,
        //     color: endVal
        //   }])
        // },
        itemStyle: {
          normal: {
            color: startVal, // 改变折线点的颜色
            lineStyle: {
              color: startVal // 改变折线颜色
            }
          }
        },
        markLine: {
          lineStyle: { color: 'red', type: 'solid' },
          data: [
            { name: '预警值', yAxis: warnVal }
          ]
        }
      };
      if (!warnVal) options.markLine = {};
      return options;
    },
    /**
     * 设置图表配置
     */
    setConfig({ title, series, xAxis, type, ...config }) {
      const defaultConfig = {
        title: {
          padding: [10, 0, 0, 10],
          textStyle: { color: '#fff' }
        },
        series: [
          {
            type: 'line',
            smooth: false,
            data: [],
            // areaStyle: {
            //   color: new this.$echarts.graphic.LinearGradient(0, 0, 0, 1, [{
            //     offset: 0,
            //     color: 'rgba(42, 155, 248, 0.9)'
            //   }, {
            //     offset: 1,
            //     color: 'rgba(42, 155, 248, 0.1)'
            //   }])
            // },
            itemStyle: {
              normal: {
                color: 'rgba(42, 155, 248)', // 改变折线点的颜色
                lineStyle: {
                  color: 'rgba(69, 191, 161, 1)' // 改变折线颜色
                }
              }
            },
            markLine: {
              lineStyle: {
                color: 'red',
                type: 'solid'
              }
            }
          }
        ],
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: this.xAxisData,
          axisLine: { // 轴线
            show: false
          },
          axisTick: { // 刻度
            show: true
          },
          axisLabel: {
            color: '#bac4ff'
          }
        },
        toolbox: {
          itemSize: 20,
          iconStyle: {
            color: 'red'
          },
          emphasis: {
            iconStyle: {
              color: '#bac4ff'
            }
          },
          // feature: {
          //   myTool1: {
          //     show: true,
          //     title: '查看历史记录',
          //     icon: `image://${historyImage}`,
          //     onclick: () => {
          //       this.getHistory(type);
          //     }
          //   }
          // }
          dataZoom: [
            {
              type: 'inside',
              start: 0,
              // end: 50,
              minValueSpan: 5,
              // maxValueSpan: 5,
              zoomLock: false
            }
          ]
        }
      };
      if (this.$checkType(title) === 'object') {
        defaultConfig.title = {
          ...defaultConfig.title,
          ...title
        };
      }
      if (this.$checkType(xAxis) === 'object') {
        defaultConfig.xAxis = {
          ...defaultConfig.xAxis,
          ...xAxis
        };
      }
      if (Array.isArray(series)) {
        defaultConfig.series = series;
      } else if (this.$checkType(series) === 'object') {
        Object.keys(series).forEach(key => {
          defaultConfig.series[0][key] = series[key];
        });
      }
      if (this.$checkType(config) === 'object') {
        Object.assign(defaultConfig, config);
      }
      return defaultConfig;
    },
    setAlarmScroll() {
      const mainEle = document.querySelector('.scroll-container');
      const ele = document.querySelector('.info-list');
      const itemEl = document.querySelector('.info-list .info-item');
      if (!itemEl) return;
      const itemHeight = itemEl.offsetHeight;
      const childH = this.alarmList.length * (itemHeight + this.$setRem(10, false));
      this.hasCopy = childH > mainEle.offsetHeight;
      if (!this.hasCopy) return;
      if (mainEle.scrollTop >= ele.scrollHeight) {
        mainEle.scrollTop = 0;
      } else {
        mainEle.scrollTop++;
      }
      this.scrollId = window.requestAnimationFrame(this.setAlarmScroll);
    },
    // 关闭滚动
    handleMouseenter() {
      this.scrollId && window.cancelAnimationFrame(this.scrollId);
    },
    // 触发滚动
    handleMouseleave() {
      this.setAlarmScroll();
    },
  }
};
</script>

<style scoped lang="scss">
  @import '../../../assets/styles/main';

  .weather-page {
    width: 100%;
    height: 100%;
    background: $menuBg;
    main {
      width: 100%;
      height: calc(100% - 40px);
      padding: 20px;
      .echarts-list {
        width: 100%;
        height: 100%;
        display: flex;
        justify-content: space-between;
        flex-wrap: wrap;
        .echarts-item {
          width: 33%;
          height: 32%;
          background: $mainBg;
          border-radius: 6px;
          position: relative;
          color: #fff;
          overflow: hidden;
          &:after {
            display: block;
            content: '';
            position: absolute;
            top: -5px;
            left: -16px;
            width: 50px;
            height: 50px;
            border-radius: 50%;
            border: 15px solid $mainColor;
            opacity: .1;
            pointer-events: none;
          }
          .empty-text {
            position: absolute;
            width: 100%;
            height: 100%;
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 20px;
            color: $disabledBg;
          }
          i {
            font-size: 18px;
            cursor: pointer;
            padding: 2px;
          }
          .title {
            width: 100%;
            height: 50px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0 10px;
            span {
              font-size: 17px;
              font-weight: bold;
            }
          }
        }
      }
    }
    .scroll-container {
      width: 100%;
      height: calc(100% - 55px);
      overflow: hidden;
      .info-list {
        padding: 0 10px;
        position: relative;
        .info-item {
          width: 100%;
          height: 50px;
          padding: 0 10px;
          display: flex;
          justify-content: space-between;
          align-items: center;
          overflow: hidden;
          color: #fff;
          font-size: 13px;
          background-color: $menuBg;
          border-radius: 5px;
          margin-bottom: 10px;
          .time {
            width: 150px;
            display: inline-block;
          }
          .name {
            width: 150px;
            display: inline-block;
          }
          .detail {
            width: 200px;
            color: red;
            display: inline-block;
          }
        }
      }
    }
  }
</style>
